<script setup>
import { ref, onMounted } from "vue";
import { getEmpList } from "@/api/emp.js";
import { deleteEmp } from "@/api/emp.js";
import { ElMessage } from "element-plus";
import { ElMessageBox } from "element-plus";
import { updateEmp } from "@/api/emp.js";
import { getDeptList } from "@/api/dept.js";
import { checkPassword, updatePassword } from "@/api/emp.js";
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star
} from "@element-plus/icons-vue";
//引入路由
import { useRouter } from "vue-router";
import { DiagnosticCategory } from "typescript";
const router = useRouter();
const tableData = ref([]);
//分页
const page = ref(1); // 当前页
const pageSize = ref(10); // 每页显示的条数
const total = ref(0); //// 总条数
const dept = ref([]); //部门信息
const searchKeyword = ref(""); //搜索关键字
//定义emp对象
let emp = ref({
  employee_id: "",
  account_status: 1
});
const dialogVisible = ref(false); // 控制弹框显示
const selectedEmployeeId = ref(null); // 当前选中的员工 ID
// 表单数据
const passwordForm = ref({
  oldPassword: "",
  newPassword: "",
  confirmPassword: ""
});
const passwordRules = ref({
  newPassword: [{ required: true, message: "请输入新密码", trigger: "blur" }],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error("新密码和确认密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});
// 打开修改密码弹框
const openPasswordDialog = employeeId => {
  console.log("openPasswordDialog", employeeId);
  selectedEmployeeId.value = employeeId;
  // 清空表单数据
  passwordForm.value = {
    oldPassword: "",
    newPassword: "",
    confirmPassword: ""
  };
};
const passwordFormRef = ref(null);
// 提交修改密码
const submitPasswordChange = async () => {
  try {
    // 验证表单数据，密码和确认密码是否一致
    await passwordFormRef.value.validate();
    // 验证原密码是否正确
    const checkRes = await checkPassword(
      selectedEmployeeId.value,
      passwordForm.value.oldPassword
    );
    if (checkRes.code !== 200) {
      // ElMessage.error(checkRes.msg);
      return;
    }
    console.log("checkResaaaa");
    // 修改密码
    const updateRes = await updatePassword(
      selectedEmployeeId.value,
      passwordForm.value.newPassword
    );
    if (updateRes.code === 200) {
      ElMessage.success("密码修改成功");
      dialogVisible.value = false;
    } else {
      ElMessage.error("密码修改失败");
    }
  } catch (error) {
    console.error("请求失败:", error); // 打印错误信息
    ElMessage.error("请求失败，请稍后重试");
  }
};
//每页记录数变化
function chgsize(size) {
  //更改每页显示的条数
  pageSize.value = size;
  //从当前页开始
  page.value = 1;
  //重新查询数据
  initData();
}
//页面发生变化
function chgpg(pg) {
  //更改当前页
  page.value = pg;
  //重新查询数据
  initData();
}
//修改数据
function update(employee_id) {
  console.log("update:" + employee_id);
  router.push({
    path: "/emp/update",
    query: { employee_id }
  });
}
// 查询数据
async function initData() {
  let data = {
    page: page.value,
    pageSize: pageSize.value,
    department_id: emp.value.department_id,
    e_name: searchKeyword.value,
    contact_info: searchKeyword.value
  };
  let res = await getEmpList(data);
  if (res.code === 200) {
    tableData.value = res.data.data;
    //接收分页信息
    page.value = res.data.page;

    pageSize.value = res.data.pageSize;

    total.value = res.data.total;
  }
  //部门信息
  try {
    let res = await getDeptList(0);
    if (res.code === 200) {
      dept.value = transformDeptData1(res.data);
    } else {
      console.error("获取部门数据失败:", res.message);
    }
  } catch (error) {
    console.error("请求部门数据时出错:", error);
  }
}
//部门信息转化方法
function transformDeptData1(data) {
  return data.map(item => ({
    value: item.dept_id,
    label: item.dept_name,
    children: item.children ? transformDeptData1(item.children) : []
  }));
}
// 生命周期
onMounted(() => {
  initData();
});
// 定义一个方法来更新account_status的值
const updateAccountStatus = async (row, status) => {
  // status: 1 启用 2 关闭
  console.log("updateAccountStatus", status, row.employee_id);
  emp.value.account_status = status;
  emp.value.employee_id = row.employee_id;
  let res = await updateEmp(emp.value);
  if (res.code === 200) {
    ElMessage.success("状态修改成功");
    initData();
  }
  row.account_status = status;
};
//添加客户
function add() {
  router.push("/emp/add");
}
// 删除客户
async function delEmp(employee_id) {
  console.log("id:" + employee_id);

  // 使用 ElMessageBox 显示确认弹框
  ElMessageBox.confirm("确定要删除吗？", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    showCancelButton: false, // 不显示取消按钮
    closeOnClickModal: true, // 点击模态框外部可以关闭
    closeOnPressEscape: true // 按下 ESC 键可以关闭
  })
    .then(async () => {
      // 用户点击确定后执行删除操作
      const res = await deleteEmp(employee_id);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        initData();
      }
    })
    .catch(() => {
      // 用户点击取消或关闭弹框时不执行任何操作
      console.log("删除操作已取消");
    });
}
//部门搜索
const handleDepartmentChange = selectedDepartmentId => {
  emp.value.department_id = selectedDepartmentId;
  console.log("Selected Department ID:", emp.value.mpdepartment_id);
};
//搜索
function handleSearch() {
  initData();
}
//重置
function handleReset() {
  searchKeyword.value = "";
  emp.value.department_id = "";
  initData();
}
</script>

<template>
  <div>
    <!-- 搜索框 -->
    <div>
      <el-form :inline="true" :model="emp">
        <el-form-item label="员工信息">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入姓名或联系方式"
          />
        </el-form-item>
        <el-form-item label="所属部门：" prop="department_id">
          <el-tree-select
            v-model="emp.department_id"
            :data="dept"
            clearable="true"
            :render-after-expand="false"
            style="width: 430px; margin-right: 0"
            @change="handleDepartmentChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 添加按钮 -->
    <div style="text-align: right; margin-right: 55px; margin-bottom: 15px">
      <el-button type="primary" @click="add">添加</el-button>
    </div>
    <el-table :data="tableData">
      <el-table-column
        prop="e_name"
        label="姓名"
        width="80"
        header-align="center"
        align="center"
      />
      <el-table-column
        prop="contact_info"
        label="联系方式"
        width="100"
        header-align="center"
        align="center"
      />
      <el-table-column
        prop="dept_name"
        label="所属部门"
        header-align="center"
        align="center"
      />
      <el-table-column
        prop="position"
        label="职务"
        header-align="center"
        align="center"
      />
      <el-table-column
        prop="account"
        label="账号"
        header-align="center"
        align="center"
      />
      <el-table-column
        prop="type_name"
        label="类型"
        header-align="center"
        align="center"
      />
      <el-table-column
        prop="annual_target"
        label="年度业绩"
        header-align="center"
        align="center"
      />
      <el-table-column
        prop="completed_performance"
        label="已完成业绩"
        width="180"
        header-align="center"
        align="center"
      />
      <el-table-column
        prop="completion_rate"
        label="完成率"
        header-align="center"
        align="center"
      />
      <el-table-column
        prop="role_name"
        label="角色"
        header-align="center"
        align="center"
      />
      <el-table-column
        prop="emp.account_status"
        label="账号状态(启用/关闭)"
        header-align="center"
        width="95"
        align="center"
      >
        <template #default="scope">
          <el-switch
            v-model="scope.row.account_status"
            :active-value="1"
            :inactive-value="2"
            @change="updateAccountStatus(scope.row, $event)"
          />
          <!-- active-text="启用" -->
          <!-- active-text="启用" inactive-text="关闭" -->
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" header-align="center">
        <template #default="scope"
          ><el-button
            type="primary"
            @click="
              openPasswordDialog(scope.row.employee_id, (dialogVisible = true))
            "
            >重置密码</el-button
          >
          <!-- 修改密码弹框 -->
          <el-dialog
            v-model="dialogVisible"
            title="修改密码"
            width="30%"
            :modal="false"
          >
            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              label-width="100px"
              :rules="passwordRules"
            >
              <el-form-item label="原密码" prop="oldPassword">
                <el-input
                  v-model="passwordForm.oldPassword"
                  type="password"
                  placeholder="请输入原密码"
                />
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  placeholder="请输入新密码"
                />
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="请再次输入新密码"
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitPasswordChange"
                >确认修改</el-button
              >
            </template>
          </el-dialog>
          &nbsp;
          <el-button type="primary" @click="update(scope.row.employee_id)"
            >编辑</el-button
          >
          <el-button type="primary" @click="delEmp(scope.row.employee_id)"
            >删除</el-button
          ></template
        >
      </el-table-column>
    </el-table>

    <!-- //分页 -->
    <el-pagination
      background
      :page-size="pageSize"
      layout="total,sizes,prev, pager, next,jumper"
      :total="total"
      @size-change="chgsize"
      @current-change="chgpg"
    />
  </div>
</template>

<style scoped>
/* 根据需要添加样式 */
</style>
